#include "common.h"

TIM_TypeDef *basic_timer6 = TIM6;
TIM_TypeDef *basic_timer7 = TIM7;

struct timer6_count_variable timer6_count;

void init_timer6(void)
{
    basic_timer6 = TIM6;
    rcc_reg->APB1ENR |= (1 << 4);
    basic_timer6->CR1 |= (1);
    basic_timer6->DIER |= (1 << 0);
    basic_timer6->PSC = 359;
    basic_timer6->ARR = 1000 - 1;

    // nvic_reg->ISER[1] = (1<<22);
    NVIC_SetPriority(TIM6_IRQn, 1);
    NVIC_EnableIRQ(TIM6_IRQn);
    basic_timer6->CR1 |= (1 << 0);
}

void TIM6_IRQHandler(void)
{
    basic_timer6->SR = 0;
    add_timer_count_variable((struct time_count *)&timer6_count, sizeof(struct timer6_count_variable) / sizeof(struct time_count));
    // adc1->CR2 |= (1<<22);
}

unsigned int get_running_time(struct time_count *p_time_count)
{
    return (p_time_count->count * TIMER_6_BASE);
}

unsigned int get_time_benchmark(unsigned int time)
{
    return time / TIMER_6_BASE;
}

void set_time_satisfy(struct time_count *p_time_count)
{
    p_time_count->count = p_time_count->benchmark + 1;
}

void set_time_delay(struct time_count *p_time_count, unsigned int delay_ms)
{
    p_time_count->run       = 0;
    p_time_count->count     = 0;
    p_time_count->benchmark = get_time_benchmark(delay_ms);
    p_time_count->run       = 1;
}

unsigned int judge_time_delay(struct time_count *p_time_count)
{
    unsigned char ret = 0;
    if (1 == p_time_count->run) {
        if (p_time_count->benchmark <= p_time_count->count) {
            ret = 1;
        } else {
            ret = 0;
        }
    } else {
        ret = 0;
    }
    return ret;
}

void clear_time_count(struct time_count *p_time_count)
{
    p_time_count->run       = 0;
    p_time_count->count     = 0;
    p_time_count->benchmark = 0;
}

void add_timer_count_variable(struct time_count *p_time_count, unsigned int num)
{
    unsigned char i = 0;
    for (i = 0; i < num; i++) {
        if (1 == p_time_count->run) {
            p_time_count->count++;
        }
        p_time_count++;
    }
}
